/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import controller.EventManager;
import controller.UserManager;
import entity.Event;
import entity.User;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.validation.constraints.Pattern;
import org.apache.commons.codec.digest.DigestUtils;
import org.primefaces.json.JSONException;
import utility.Forecast;

@ManagedBean
@SessionScoped
public class LoginBean implements Serializable{
   
    @EJB
    private UserManager userMgr;
    @EJB
    private EventManager evtMgr;
    
    private User user;
    private String errore;    
    @Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",
                        message = "Email: Validation Error: Invalid Email.")
    private String email;
    private String password;
    private String msg;
    private String nickname;
    private String name;
    private String surname;
    private Date today;
    private boolean loggedIn;
    private List<Forecast> weathers;
    private List<Event> eventsTakePart;
    private List<Event> eventsOrganized;
    private List<Event> eventPassed;
    private String privacy;
    @ManagedProperty( value = "#{navigationBean}" )
    private NavigationBean navigationBean;
    
    @ManagedProperty( value = "#{weatherBean}")
    private WeatherBean weatherBean;

    
    @PostConstruct
    public void init() {
        today= new Date();
        User user = new User();
        email = "";
        password = "";
        msg = "";
        nickname = "";
        name = "";
        surname = "";
        errore = "";
        loggedIn=false;
        weathers = new ArrayList<Forecast>();
        eventPassed= new ArrayList<Event>();
        eventsOrganized = new ArrayList<Event>();
        eventsTakePart = new ArrayList<Event>();
        
    }

    
    public String login() throws JSONException, IOException
    {
        List<User> users = userMgr.getAllUsers();
        String hashPswInserted = DigestUtils.sha256Hex( password );
        if(users.size() > 0 ){              
            for( User u : users )
            {
                if( u.getEmail().equalsIgnoreCase(email ) && u.getPassword().equals( hashPswInserted ) )
                {
                    msg = "login corretto";
                    loggedIn = true;
                    user = u;
                    // inizializzazione liste principali e meteo
                    eventsTakePart = evtMgr.getAllEventsTakePart(user);
                    eventsOrganized = evtMgr.getAllEventsOrganized(user);
                    eventsTakePart.addAll(eventsOrganized);
                    listControl();
                    weathers = weatherBean.loadWeather(weathers,eventsTakePart);
                    
                    callString();
                    resetFields();
                    return navigationBean.redirectToPersonalPage();
                }
            }
        }
        System.out.println("Utente non trovato");
        
        msg = "utente non trovato";
        resetFields();
        return navigationBean.redirectToLoginPage();
    }
    
    public String refreshPage()
    {
        resetFields();
        setErrore("");
        return navigationBean.redirectToLoginPage();
    }
    
    public String register()
    {
        List<User> users = userMgr.getAllUsers();
        if(users.isEmpty()== false){
            for( User u: users )
            {
                if( u.getEmail().equalsIgnoreCase( email ) || u.getNickname().equals( nickname ) )
                {
                    System.out.println("Utente gia registrato");
                    setErrore( "Utente già registrato" );
                    return navigationBean.redirectToLoginPage();
                }
            }
        }
        String hashPsw = DigestUtils.sha256Hex( password );
 
        user = new User(nickname,name,surname,email,hashPsw,1);
        userMgr.save(user);
        System.out.println("Utente registrato: "+user.getName());
        user=null;
        resetFields();
        setErrore("");
        return navigationBean.redirectToLoginPage();         
    }
    
    public String logout()
    {    
        user = null;
        loggedIn = false;
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return navigationBean.toLoginPage();
    }
    
    public String getErrore() {
        return errore;
    }

    public void setErrore(String errore) {
        this.errore = errore;
    }

    private void resetFields() {
        setNickname("");
        setName("");
        setSurname("");
        setPassword("");
        setEmail("");
    }
    public String changeCalendarPrivacy(){
        if(user.getPublicCal()==0)
            user.setPublicCal(1);
        else
            user.setPublicCal(0);
        
        if(userMgr.UpdateUser(user)== true)
        { 
            callString();
            System.out.println("utente aggiornato");
        }
        else
            System.out.println("utente non aggiornato");
        return navigationBean.redirectToSettingsPage();    
    }
    
    public String getPrivacy() {
        return privacy;
    }

    public void setPrivacy(String privacy) {
        this.privacy = privacy;
    }
    
    public void callString() {
        if(user.getPublicCal()==0)
            setPrivacy("Private");
        else
            setPrivacy("Public");
    }
    
  
      private void listControl(){
        
        int i = 0;
        while( i < eventsTakePart.size() )
        {
            if( eventsTakePart.get( i ).getDateStart().before(today)){
                eventPassed.add(eventsTakePart.get( i ));             
                eventsTakePart.remove( i );
            }else
                i++;
        }
    }
     

    public List<Event> getEventsTakePart() {
        return eventsTakePart;
    }

    public void setEventsTakePart(List<Event> eventsTakePart) {
        this.eventsTakePart = eventsTakePart;
    }

    public List<Event> getEventsOrganized() {
        return eventsOrganized;
    }

    public void setEventsOrganized(List<Event> eventsOrganized) {
        this.eventsOrganized = eventsOrganized;
    }
      
    
    public NavigationBean getNavigationBean() {
        return navigationBean;
    }

    public void setNavigationBean(NavigationBean navigationBean) {
        this.navigationBean = navigationBean;
    }
    
    public List<Forecast> getWeathers() {
        return weathers;
    }
    
    public boolean isLoggedIn() {
        return loggedIn;
    }

    public void setLoggedIn(boolean loggedIn) {
        this.loggedIn = loggedIn;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }
    
    public String getMsg() 
    {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
    public String getEmail()
    {
        return email;
    }
    public void setEmail( String email )
    {
        this.email = email;
    }
    public String getPassword()
    {
        return password;
    }
    public void setPassword( String password )
    {
        this.password = password;
    }
         
      public WeatherBean getWeatherBean() {
        return weatherBean;
    }

    public void setWeatherBean(WeatherBean weatherBean) {
        this.weatherBean = weatherBean;
    }

    public void setWeathers(List<Forecast> weathers) {
        this.weathers = weathers;
    }

    public List<Event> getEventPassed() {
        return eventPassed;
    }

    public void setEventPassed(List<Event> eventPassed) {
        this.eventPassed = eventPassed;
    }

    
    
    
}
